package com.example.demo.elasticsearch;

import com.example.demo.mybatisPlus.entity.Product;
import com.example.demo.mybatisPlus.service.ProductService;
import lombok.AllArgsConstructor;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@AllArgsConstructor
public class MyEsController {

    private ProductService productService;
    private static String indexName = "product";

    /**
     * 新增一条
     */
    @RequestMapping("/es/add")
    public String testEsAdd() {
        Product product = productService.list().get(0);
        return EsUtils.addData(product, indexName, product.getId().toString());
    }

    /**
     * 新增多条
     */
    @RequestMapping("/es/add/list")
    public String testEsAddList() {
        List<Product> products = productService.list();
        return EsUtils.insertBatch(indexName, products);
    }

    /**
     * 更改
     */
    @RequestMapping("/es/update")
    public String testEsUpdate() {
        Product product = productService.list().get(0);
        product.setStatus(2);
        return EsUtils.updateData(product, indexName, product.getId().toString());
    }

    /**
     * 根据ID删除
     */
    @RequestMapping("/es/delete/id")
    public String testEsDeleteById() {
        Product product = productService.list().get(0);
        return EsUtils.deleteById(indexName, product.getId().toString());
    }

    /**
     * 条件删除
     */
    @RequestMapping("/es/delete/query")
    public void testEsDeleteQuery() {
        Product product = productService.list().get(1);
//        QueryBuilder queryBuilder = QueryBuilders.matchQuery("id", product.getId());
        EsUtils.deleteByQuery(indexName, QueryBuilders.matchAllQuery());
    }

    /**
     * 删除索引
     */
    @RequestMapping("/es/delete/index")
    public void testEsDeleteIndex() {
        EsUtils.deleteIndex(indexName);
    }

    /** 数据查询 */
    /**
     * 分页分词关键词查询
     * 使用QueryBuilder
     * termQuery("key", obj) 完全匹配
     * termsQuery("key", obj1, obj2..)   一次匹配多个值
     * matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性
     * multiMatchQuery("text", "field1", "field2"..);  匹配多个字段, field有通配符忒行
     * matchAllQuery();         匹配所有文件
     * 组合查询
     * must(QueryBuilders) :   AND
     * mustNot(QueryBuilders): NOT
     * should:                  : OR
     * percent_terms_to_match：匹配项（term）的百分比，默认是0.3
     * min_term_freq：一篇文档中一个词语至少出现次数，小于这个值的词将被忽略，默认是2
     * max_query_terms：一条查询语句中允许最多查询词语的个数，默认是25
     * stop_words：设置停止词，匹配时会忽略停止词
     * min_doc_freq：一个词语最少在多少篇文档中出现，小于这个值的词会将被忽略，默认是无限制
     * max_doc_freq：一个词语最多在多少篇文档中出现，大于这个值的词会将被忽略，默认是无限制
     * min_word_len：最小的词语长度，默认是0
     * max_word_len：最多的词语长度，默认无限制
     * boost_terms：设置词语权重，默认是1
     * boost：设置查询权重，默认是1
     * analyzer：设置使用的分词器，默认是使用该字段指定的分词器
     */
    @RequestMapping("/es/search/{input}")
    public List testEsSearch(@PathVariable String input) {
        /** 查询条件构造器 */
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /** 定义返回字段 */
        String[] fields = {"id", "name"};
        /** 需要返回和不返回的字段，可以是数组也可以是字符串 */
        sourceBuilder.fetchSource(fields, null);
        /** 设置根据哪个字段进行排序查询 */
//        sourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.DESC));
        /** 定义条件构造器 */
        // 2.创建BoolQueryBuilder对象
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        // 3.设置boolQueryBuilder条件   boost权重
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders
                .matchPhraseQuery("name", "中华").analyzer("ik_max_word").boost(100);
        MatchPhraseQueryBuilder matchPhraseQueryBuilder2 = QueryBuilders
                .matchPhraseQuery("name", "国").analyzer("ik_max_word").boost(50);
//        RangeQueryBuilder rangeQueryBuilder = QueryBuilders
//                .rangeQuery("字段")
//                .from("时间段");
        MatchPhraseQueryBuilder matchPhraseQueryBuilder3 = QueryBuilders
                .matchPhraseQuery("status", "0");
        // 子boolQueryBuilder条件条件，用来表示查询条件or的关系
        BoolQueryBuilder childBoolQueryBuilder = new BoolQueryBuilder()
                .should(matchPhraseQueryBuilder)
                .should(matchPhraseQueryBuilder2);
        // 4.添加查询条件到boolQueryBuilder中
        queryBuilder
                .must(childBoolQueryBuilder)
//                .must(rangeQueryBuilder);
                .must(matchPhraseQueryBuilder3);
        return EsUtils.searchDataPage(indexName, 1, 50, sourceBuilder, queryBuilder);
    }

}
